package com.example.demo.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.demo.config.LoginUser;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.util.StringUtils;
import java.util.*;

public abstract class JwtUtils {
    private static final String APP_KEY="demo2000";
    public static final long EXPIRE = 1000 * 60 * 60 * 24 * 365L;

    /** 创建token */
    public static String createTokenFromMap(Map<String,Object> map) {
        return JWT.create()
                .withIssuer("demo")
                .withClaim("map", map)
                .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRE))
                .sign(Algorithm.HMAC256(APP_KEY));
    }
    /** 验证,解码token */
    public static Map<String,Object> getMapFromToken(String token) {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(APP_KEY))
                .withIssuer("demo")
                .build();
        DecodedJWT decodedJWT = verifier.verify(token);
        return decodedJWT.getClaim("map").asMap();
    }
    public static String createTokenFromUser(LoginUser user){
        Map<String,Object> map =new HashMap<>();
        map.put("id",user.getId());
        map.put("username",user.getUsername());
        map.put("authorities",user.getAuthorities().toString());
        return createTokenFromMap(map);
    }
    public static LoginUser getUserFromToken(String token){
        Map<String,Object> map = getMapFromToken(token);

        if(map==null){
            return null;
        }else{
            return new LoginUser(Long.parseLong(map.get("id").toString()), map.get("username").toString(),"",getAuthorities(map.get("authorities").toString()));
        }
    }

    public static List<GrantedAuthority> getAuthorities(String authStr){
        List<GrantedAuthority> authorities = new ArrayList<>();
        authStr= StringUtils.trimLeadingCharacter(authStr,'[');
        authStr= StringUtils.trimTrailingCharacter(authStr,']');
        List<String> list = Arrays.asList(authStr.split(","));
        list.forEach(item->{
            authorities.add(new SimpleGrantedAuthority(item));
        });
        return authorities;
    }
}
